package com.ssrs.framework.extend;

import cn.hutool.core.util.StrUtil;
import com.ssrs.framework.extend.annotation.ExtendAction;
import com.ssrs.framework.extend.plugin.PluginConfig;
import com.ssrs.framework.extend.plugin.PluginException;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 扩展行为类，对应一个扩展行为
 *
 * @author ssrs
 */
public class ExtendActionConfig {
    private boolean enable;
    private PluginConfig pluginConfig;
    private String id;
    private String description;
    private String extendPointId;
    private String className;
    private IExtendAction instance = null;
    private static ReentrantLock lock = new ReentrantLock();

    public void init(PluginConfig pc, Class<?> clazz) throws PluginException {
        ExtendAction element = clazz.getAnnotation(ExtendAction.class);
        pluginConfig = pc;
        id = clazz.getName();
        description = element.description();
        extendPointId = element.extendPoint().getName();
        className = clazz.getName();
        if (StrUtil.isEmpty(id)) {
            throw new PluginException("extendAction's id is empty!");
        }
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    public boolean isEnable() {
        return enable;
    }

    public PluginConfig getPluginConfig() {
        return pluginConfig;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }


    public String getClassName() {
        return className;
    }



    public void setDescription(String description) {
        this.description = description;
    }

    public String getExtendPointId() {
        return extendPointId;
    }

    public void setExtendPointId(String extendPointId) {
        this.extendPointId = extendPointId;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public IExtendAction getInstance() {
        try {
            if (instance == null) {
                lock.lock();
                try {
                    if (instance == null) {
                        Class<?> clazz = Class.forName(className);
                        ExtendPointConfig ep = ExtendManager.getInstance().findExtendPoint(extendPointId);
                        if (ep.isChild(clazz)) {
                            throw new RuntimeException(
                                    "ExtendAction " + className + " must extends " + ep.getClassName());
                        }
                        instance = (IExtendAction) clazz.newInstance();
                    }
                } finally {
                    lock.unlock();
                }
            }
            return instance;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
